#include "SettingPage.h"

#include <QHBoxLayout>
#include <QIcon>
#include <QVBoxLayout>
#include <QSlider>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QCheckBox>
#include <QPushButton>
#include <QLabel>
#include <QComboBox>
#include <QGroupBox>
#include <QColorDialog>
#include <QFormLayout>

#include "ElaImageCard.h"
#include "ElaText.h"
#include "VTKModelStudio.h"

SettingPage::SettingPage(QWidget* parent, VTKModelStudio* studio) : ElaDialog(parent), m_studio(studio)
{
    setWindowTitle("3D模型设置");
    this->setIsFixedSize(true);
    setWindowModality(Qt::NonModal);
    setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
    resize(600, 800);

    setupUI();
}

SettingPage::~SettingPage()
{
}

void SettingPage::setupUI()
{
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(20, 25, 20, 20);

    // 相机控制组
    QGroupBox* cameraGroup = new QGroupBox("相机控制");
    QFormLayout* cameraLayout = new QFormLayout(cameraGroup);

    // 相机位置
    QHBoxLayout* posLayout = new QHBoxLayout();
    m_cameraPosXSpin = new QDoubleSpinBox();
    m_cameraPosYSpin = new QDoubleSpinBox();
    m_cameraPosZSpin = new QDoubleSpinBox();

    for (auto spin : {m_cameraPosXSpin, m_cameraPosYSpin, m_cameraPosZSpin})
    {
        spin->setRange(-100, 100);
        spin->setSingleStep(1.0);
        spin->setDecimals(0);
        posLayout->addWidget(new QLabel(spin == m_cameraPosXSpin ? "X:" : spin == m_cameraPosYSpin ? "Y:" : "Z:"));
        posLayout->addWidget(spin);
    }
    cameraLayout->addRow("位置:", posLayout);

    // 相机旋转
    QHBoxLayout* yawLayout = new QHBoxLayout();
    m_yawSlider = new QSlider(Qt::Horizontal);
    m_yawSlider->setRange(-180, 180);
    m_yawLabel = new QLabel("0°");
    yawLayout->addWidget(new QLabel("航向:"));
    yawLayout->addWidget(m_yawSlider);
    yawLayout->addWidget(m_yawLabel);
    cameraLayout->addRow(yawLayout);

    QHBoxLayout* pitchLayout = new QHBoxLayout();
    m_pitchSlider = new QSlider(Qt::Horizontal);
    m_pitchSlider->setRange(-180, 180);
    m_pitchLabel = new QLabel("0°");
    pitchLayout->addWidget(new QLabel("俯仰:"));
    pitchLayout->addWidget(m_pitchSlider);
    pitchLayout->addWidget(m_pitchLabel);
    cameraLayout->addRow(pitchLayout);

    QHBoxLayout* rollLayout = new QHBoxLayout();
    m_rollSlider = new QSlider(Qt::Horizontal);
    m_rollSlider->setRange(-180, 180);
    m_rollLabel = new QLabel("0°");
    rollLayout->addWidget(new QLabel("横滚:"));
    rollLayout->addWidget(m_rollSlider);
    rollLayout->addWidget(m_rollLabel);
    cameraLayout->addRow(rollLayout);

    m_resetCameraBtn = new QPushButton("重置相机");
    cameraLayout->addRow(m_resetCameraBtn);

    // 模型外观组
    QGroupBox* modelGroup = new QGroupBox("模型外观");
    QFormLayout* modelLayout = new QFormLayout(modelGroup);

    m_modelColorBtn = new QPushButton("选择颜色");
    modelLayout->addRow("颜色:", m_modelColorBtn);

    QHBoxLayout* opacityLayout = new QHBoxLayout();
    m_opacitySlider = new QSlider(Qt::Horizontal);
    m_opacitySlider->setRange(0, 100);
    m_opacitySlider->setValue(100);
    m_opacityLabel = new QLabel("100%");
    opacityLayout->addWidget(m_opacitySlider);
    opacityLayout->addWidget(m_opacityLabel);
    modelLayout->addRow("透明度:", opacityLayout);

    m_representationCombo = new QComboBox();
    m_representationCombo->addItems({"点", "线框", "表面"});
    m_representationCombo->setCurrentIndex(2);
    modelLayout->addRow("显示模式:", m_representationCombo);

    // 背景控制组
    QGroupBox* bgGroup = new QGroupBox("背景控制");
    QFormLayout* bgLayout = new QFormLayout(bgGroup);

    m_bgColorBtn = new QPushButton("选择背景色1");
    m_bgColor2Btn = new QPushButton("选择背景色2");
    m_gradientBgCheck = new QCheckBox("启用渐变背景");

    // 背景透明度控制
    QHBoxLayout* transparencyLayout = new QHBoxLayout();
    QSlider* transparencySlider = new QSlider(Qt::Horizontal);
    transparencySlider->setRange(0, 100);
    transparencySlider->setValue(100);
    QLabel* transparencyLabel = new QLabel("100%");
    transparencyLayout->addWidget(transparencySlider);
    transparencyLayout->addWidget(transparencyLabel);

    bgLayout->addRow("背景色1:", m_bgColorBtn);
    bgLayout->addRow("背景色2:", m_bgColor2Btn);
    bgLayout->addRow(m_gradientBgCheck);
    bgLayout->addRow("背景透明度:", transparencyLayout); 


    // 光照控制组
    QGroupBox* lightGroup = new QGroupBox("光照控制");
    QFormLayout* lightLayout = new QFormLayout(lightGroup);

    m_lightEnabledCheck = new QCheckBox("启用光照");
    m_lightEnabledCheck->setChecked(false);

    QHBoxLayout* intensityLayout = new QHBoxLayout();
    m_lightIntensitySlider = new QSlider(Qt::Horizontal);
    m_lightIntensitySlider->setRange(0, 100);
    m_lightIntensitySlider->setValue(50);
    m_lightIntensityLabel = new QLabel("0.50");
    intensityLayout->addWidget(m_lightIntensitySlider);
    intensityLayout->addWidget(m_lightIntensityLabel);

    // 新增：光源位置控制
    QHBoxLayout* lightPosLayout = new QHBoxLayout();
    m_lightPosXSpin = new QDoubleSpinBox();
    m_lightPosYSpin = new QDoubleSpinBox();
    m_lightPosZSpin = new QDoubleSpinBox();

    for (auto spin : {m_lightPosXSpin, m_lightPosYSpin, m_lightPosZSpin})
    {
        spin->setRange(-100, 100);
        spin->setSingleStep(0.1);
        spin->setDecimals(2);
        lightPosLayout->addWidget(new QLabel(spin == m_lightPosXSpin ? "X:" : spin == m_lightPosYSpin ? "Y:" : "Z:"));
        lightPosLayout->addWidget(spin);
    }

    // 新增：光源焦点控制
    QHBoxLayout* lightFocalLayout = new QHBoxLayout();
    m_lightFocalXSpin = new QDoubleSpinBox();
    m_lightFocalYSpin = new QDoubleSpinBox();
    m_lightFocalZSpin = new QDoubleSpinBox();

    for (auto spin : {m_lightFocalXSpin, m_lightFocalYSpin, m_lightFocalZSpin})
    {
        spin->setRange(-100, 100);
        spin->setSingleStep(0.1);
        spin->setDecimals(2);
        lightFocalLayout->addWidget(new QLabel(spin == m_lightFocalXSpin ? "X:" : spin == m_lightFocalYSpin ? "Y:" : "Z:"));
        lightFocalLayout->addWidget(spin);
    }

    // 重置光源位置按钮
    m_resetLightBtn = new QPushButton("重置光源位置");

    lightLayout->addRow(m_lightEnabledCheck);
    lightLayout->addRow("光照强度:", intensityLayout);
    lightLayout->addRow("光源位置:", lightPosLayout);
    lightLayout->addRow("光源焦点:", lightFocalLayout);
    lightLayout->addRow(m_resetLightBtn);

    // 坐标轴控制组
    QGroupBox* axesGroup = new QGroupBox("坐标轴");
    QFormLayout* axesLayout = new QFormLayout(axesGroup);

    m_axesWorldVisibleCheck = new QCheckBox("显示世界坐标轴");
    axesLayout->addRow(m_axesWorldVisibleCheck);

    // 模型姿态指示器控制组
    QGroupBox* orientationGroup = new QGroupBox("模型姿态指示器");
    QFormLayout* orientationLayout = new QFormLayout(orientationGroup);

    m_orientationMarkerVisibleCheck = new QCheckBox("显示模型姿态指示器");
    m_orientationMarkerVisibleCheck->setChecked(false);  // 默认显示

    m_orientationMarkerTypeCombo = new QComboBox();
    m_orientationMarkerTypeCombo->addItems({"坐标轴", "立方体"});
    m_orientationMarkerTypeCombo->setCurrentIndex(0);  // 默认坐标轴

    m_orientationMarkerInteractiveCheck = new QCheckBox("允许移动指示器");
    m_orientationMarkerInteractiveCheck->setChecked(false);  // 默认允许交互

    orientationLayout->addRow(m_orientationMarkerVisibleCheck);
    orientationLayout->addRow("姿态指示器类型:", m_orientationMarkerTypeCombo);
    orientationLayout->addRow(m_orientationMarkerInteractiveCheck);

    // 过滤器组
    QGroupBox* filterGroup = new QGroupBox("过滤器");
    QFormLayout* filterLayout = new QFormLayout(filterGroup);

    m_shrinkFilterCheck = new QCheckBox("启用收缩过滤器");
    m_clipFilterCheck = new QCheckBox("启用裁剪过滤器");

    filterLayout->addRow(m_shrinkFilterCheck);
    filterLayout->addRow(m_clipFilterCheck);

    // 交互控制组
    QGroupBox* interactionGroup = new QGroupBox("鼠标交互控制");
    QFormLayout* interactionLayout = new QFormLayout(interactionGroup);

    m_mouseInteractionCheck = new QCheckBox("启用鼠标交互");
    m_mouseInteractionCheck->setChecked(false);
    interactionLayout->addRow(m_mouseInteractionCheck);

    // 添加到主布局
    mainLayout->addWidget(cameraGroup);
    mainLayout->addWidget(modelGroup);
    mainLayout->addWidget(bgGroup);
    mainLayout->addWidget(lightGroup);
    mainLayout->addWidget(axesGroup);
    mainLayout->addWidget(orientationGroup);  // 新增模型姿态指示器组
    mainLayout->addWidget(filterGroup);
    mainLayout->addWidget(interactionGroup);
    mainLayout->addStretch();

    // 连接信号槽
    connect(m_cameraPosXSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &SettingPage::onCameraPositionChanged);
    connect(m_cameraPosYSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &SettingPage::onCameraPositionChanged);
    connect(m_cameraPosZSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &SettingPage::onCameraPositionChanged);

    connect(m_yawSlider, &QSlider::valueChanged, this, &SettingPage::onDirectionControl);
    connect(m_pitchSlider, &QSlider::valueChanged, this, &SettingPage::onDirectionControl);
    connect(m_rollSlider, &QSlider::valueChanged, this, &SettingPage::onDirectionControl);

    connect(m_resetCameraBtn, &QPushButton::clicked, this, &SettingPage::onResetCamera);

    connect(m_modelColorBtn, &QPushButton::clicked, this, &SettingPage::onModelColorChanged);
    connect(m_opacitySlider, &QSlider::valueChanged, this, &SettingPage::onModelOpacityChanged);
    connect(m_representationCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &SettingPage::onModelRepresentationChanged);

    connect(m_bgColorBtn, &QPushButton::clicked, this, &SettingPage::onBackgroundColorChanged);
    connect(m_bgColor2Btn, &QPushButton::clicked, this, &SettingPage::onBackgroundColorChanged);
    connect(m_gradientBgCheck, &QCheckBox::stateChanged, this, &SettingPage::onGradientBackgroundChanged);
    // 背景透明度控制信号连接
    connect(transparencySlider, &QSlider::valueChanged, this, [=](int value) {
        if (!m_studio)
            return;

        double opacity = value / 100.0;
        //m_studio->setBackgroundTransparency(opacity);
        transparencyLabel->setText(QString("%1%").arg(value));
    });

    connect(m_lightEnabledCheck, &QCheckBox::stateChanged, this, &SettingPage::onLightEnabledChanged);
    connect(m_lightIntensitySlider, &QSlider::valueChanged, this, &SettingPage::onLightIntensityChanged);

    connect(m_axesWorldVisibleCheck, &QCheckBox::stateChanged, this, &SettingPage::onAxesWorldVisibleChanged);

    // 新增模型姿态指示器信号连接
    connect(m_orientationMarkerVisibleCheck, &QCheckBox::stateChanged, this, &SettingPage::onAttitudeMarkerVisibleChanged);
    connect(m_orientationMarkerTypeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &SettingPage::onAttitudeMarkerTypeChanged);
    connect(m_orientationMarkerInteractiveCheck, &QCheckBox::stateChanged, this, &SettingPage::onAttitudeMarkerInteractiveChanged);

    connect(m_shrinkFilterCheck, &QCheckBox::stateChanged, this, &SettingPage::onShrinkFilterChanged);
    connect(m_clipFilterCheck, &QCheckBox::stateChanged, this, &SettingPage::onClipFilterChanged);

    connect(m_mouseInteractionCheck, &QCheckBox::stateChanged, this, &SettingPage::onMouseInteractionChanged);

        // 连接新增的信号槽
    connect(m_lightPosXSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &SettingPage::onLightPositionChanged);
    connect(m_lightPosYSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &SettingPage::onLightPositionChanged);
    connect(m_lightPosZSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &SettingPage::onLightPositionChanged);

    connect(m_lightFocalXSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &SettingPage::onLightFocalPointChanged);
    connect(m_lightFocalYSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &SettingPage::onLightFocalPointChanged);
    connect(m_lightFocalZSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &SettingPage::onLightFocalPointChanged);

    connect(m_resetLightBtn, &QPushButton::clicked, this, &SettingPage::onResetLightPosition);

    // 初始化光源位置显示
    updateLightPositionDisplay();

    // 初始化标签
    updateRotationLabels();
}

void SettingPage::onCameraPositionChanged()
{
    if (!m_studio)
        return;

    double x = m_cameraPosXSpin->value();
    double y = m_cameraPosYSpin->value();
    double z = m_cameraPosZSpin->value();

    m_studio->setCameraPosition(x, y, z);
}

void SettingPage::onDirectionControl()
{
    if (!m_studio)
        return;

    m_studio->setYaw(m_yawSlider->value());
    m_studio->setPitch(m_pitchSlider->value());
    m_studio->setRoll(m_rollSlider->value());

    updateRotationLabels();
}

void SettingPage::onResetCamera()
{
    if (!m_studio)
        return;

    m_studio->resetCamera();

    // 重置UI控件
    m_cameraPosXSpin->setValue(0);
    m_cameraPosYSpin->setValue(0);
    m_cameraPosZSpin->setValue(0);

    m_yawSlider->setValue(0);
    m_pitchSlider->setValue(0);
    m_rollSlider->setValue(0);

    updateRotationLabels();
}

void SettingPage::onModelColorChanged()
{
    if (!m_studio)
        return;

    QColor color = QColorDialog::getColor(Qt::red, this, "选择模型颜色");
    if (color.isValid())
    {
        m_studio->setModelColor(color);
    }
}

void SettingPage::onModelOpacityChanged(int value)
{
    if (!m_studio)
        return;

    double opacity = value / 100.0;
    m_studio->setModelOpacity(opacity);
    m_opacityLabel->setText(QString("%1%").arg(value));
}

void SettingPage::onModelRepresentationChanged(int index)
{
    if (!m_studio)
        return;

    m_studio->setModelRepresentation(index);
}

void SettingPage::onBackgroundColorChanged()
{
    if (!m_studio)
        return;

    QPushButton* senderBtn = qobject_cast<QPushButton*>(sender());
    if (!senderBtn)
        return;

    QColor color = QColorDialog::getColor(Qt::darkGray, this, "选择背景颜色");
    if (color.isValid())
    {
        if (senderBtn == m_bgColorBtn)
        {
            m_studio->setBackgroundColor(color);
        }
        else if (senderBtn == m_bgColor2Btn)
        {
            // 获取当前背景色1
            QColor currentColor = m_studio->getBackgroundColor();

            // 设置渐变背景
            m_studio->setBackgroundGradient(currentColor.redF(), currentColor.greenF(), currentColor.blueF(), color.redF(), color.greenF(), color.blueF());
        }
    }
}

void SettingPage::onGradientBackgroundChanged(int state)
{
    if (!m_studio)
        return;

    m_studio->setGradientBackground(state == Qt::Checked);
}

void SettingPage::onLightEnabledChanged(int state)
{
    if (!m_studio)
        return;

    m_studio->setLightEnabled(state == Qt::Checked);

    // 启用光照时更新位置显示
    if (state == Qt::Checked)
    {
        updateLightPositionDisplay();
    }
}

void SettingPage::onLightIntensityChanged(int value)
{
    if (!m_studio)
        return;

    double intensity = value / 100.0;
    m_studio->setLightIntensity(intensity);
    m_lightIntensityLabel->setText(QString::number(intensity, 'f', 2));
}

// 新增：光源位置改变槽函数
void SettingPage::onLightPositionChanged()
{
    if (!m_studio)
        return;

    double x = m_lightPosXSpin->value();
    double y = m_lightPosYSpin->value();
    double z = m_lightPosZSpin->value();

    m_studio->setLightPosition(x, y, z);
}

// 新增：光源焦点改变槽函数
void SettingPage::onLightFocalPointChanged()
{
    if (!m_studio)
        return;

    double x = m_lightFocalXSpin->value();
    double y = m_lightFocalYSpin->value();
    double z = m_lightFocalZSpin->value();

    m_studio->setLightFocalPoint(x, y, z);
}

// 新增：重置光源位置
void SettingPage::onResetLightPosition()
{
    if (!m_studio)
        return;

    // 重置到默认位置
    m_studio->setLightPosition(0.0, 0.0, 1.0);
    m_studio->setLightFocalPoint(0.0, 0.0, 0.0);

    updateLightPositionDisplay();
}

// 新增：更新光源位置显示
void SettingPage::updateLightPositionDisplay()
{
    if (!m_studio)
        return;

    double x, y, z;

    // 更新光源位置
    m_studio->getLightPosition(x, y, z);
    m_lightPosXSpin->setValue(x);
    m_lightPosYSpin->setValue(y);
    m_lightPosZSpin->setValue(z);

    // 更新光源焦点
    m_studio->getLightFocalPoint(x, y, z);
    m_lightFocalXSpin->setValue(x);
    m_lightFocalYSpin->setValue(y);
    m_lightFocalZSpin->setValue(z);
}


void SettingPage::onAxesWorldVisibleChanged(int state)
{
    if (!m_studio)
        return;

    m_studio->setAxesWorldVisible(state == Qt::Checked);
}

// 新增模型姿态指示器控制函数
void SettingPage::onAttitudeMarkerVisibleChanged(int state)
{
    if (!m_studio)
        return;

    m_studio->setAttitudeMarkerVisible(state == Qt::Checked);
}

void SettingPage::onAttitudeMarkerTypeChanged(int index)
{
    if (!m_studio)
        return;

    // m_studio->setAttitudeMarkerType(index);
}

void SettingPage::onAttitudeMarkerInteractiveChanged(int state)
{
    if (!m_studio)
        return;

    m_studio->setAttitudeMarkerInteractive(state == Qt::Checked);
}

void SettingPage::onShrinkFilterChanged(int state)
{
    if (!m_studio)
        return;

    m_studio->setShrinkFilterEnabled(state == Qt::Checked);
}

void SettingPage::onClipFilterChanged(int state)
{
    if (!m_studio)
        return;

    m_studio->setClipFilterEnabled(state == Qt::Checked);
}

void SettingPage::onMouseInteractionChanged(int state)
{
    if (!m_studio)
        return;

    m_studio->setMouseInteractionEnabled(state == Qt::Checked);
}

void SettingPage::updateRotationLabels()
{
    m_yawLabel->setText(QString("%1°").arg(m_yawSlider->value()));
    m_pitchLabel->setText(QString("%1°").arg(m_pitchSlider->value()));
    m_rollLabel->setText(QString("%1°").arg(m_rollSlider->value()));
}